package com.spzx.order.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.order.configure.OrderDelayedMqConfig;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.rabbit.constant.MqConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderReceiver {

    @Autowired
    IOrderInfoService iOrderInfoService;

//    @RabbitListener(bindings = @QueueBinding(
//            exchange = @Exchange(value = MqConst.EXCHANGE_CANCEL_ORDER,durable = "true"),
//            value = @Queue(value = MqConst.QUEUE_CANCEL_ORDER,durable = "true"),
//            key = {MqConst.ROUTING_CANCEL_ORDER}
//    ))
    @RabbitListener(queues = OrderDelayedMqConfig.queue_delay_order)
    public void receiveOrder(Channel channel , Message message,String tradeNo) throws IOException {
        System.out.println("时间过期，消费者未支付，关闭订单");

        // 查询订单状态是否是未支付（0） 防止库存扣减和库存释放被重复执行
        OrderInfo orderInfo = iOrderInfoService.getOrderByOrderNo(tradeNo);
        Integer orderStatus = orderInfo.getOrderStatus();
        if (orderStatus == 0){
            iOrderInfoService.cancelOrder(tradeNo);  // 取消订单异常可将消息回滚
        }


        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PAYMENT_PAY, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true"),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void b(Channel channel, Message message, String orderNo) throws IOException{
        System.out.println("根据orderNo订单更新订单信息");
        iOrderInfoService.updateOrderStatus(orderNo);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
